{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## quick sort"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 递归版一（以最右为pivot）\n",
    "def quick_sort_0_simple(array, left, right):\n",
    "    if left <= right:\n",
    "        key = array[right]\n",
    "        i = left-1\n",
    "        for j in range(left, right):\n",
    "            if array[j] <= key:\n",
    "                i += 1\n",
    "                if i != j:\n",
    "                    array[i], array[j] = array[j], array[i]\n",
    "        array[right], array[i+1] = array[i+1], array[right]\n",
    "    else:\n",
    "        return\n",
    "    quick_sort_0_simple(array, left, i)\n",
    "    quick_sort_0_simple(array, i+2, right)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
     ]
    }
   ],
   "source": [
    "input_array=[1, 3, 5, 7, 9, 2, 4, 6, 8, 0]\n",
    "quick_sort_0_simple(input_array,0,len(input_array)-1)\n",
    "print(input_array)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 循环版\n",
    "def sortArray(nums):\n",
    "    left=0\n",
    "    right=len(nums)-1\n",
    "    st=[(left,right),]\n",
    "    while st:\n",
    "        left,right=st.pop(0)\n",
    "        if right-left<1:\n",
    "            continue\n",
    "        low=left-1\n",
    "        key=nums[right]\n",
    "        for i in range(left,right):\n",
    "            if nums[i]<=key:\n",
    "                low+=1\n",
    "                nums[low],nums[i]=nums[i],nums[low]\n",
    "        nums[low+1],nums[right]=nums[right],nums[low+1]\n",
    "        st.append((left, low))\n",
    "        st.append((low+2, right))\n",
    "    return nums"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
